﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BuscoPre.Domain;
using BuscoPre.Repository;
using BuscoPre.TagCloudGenerator;
using BuscoPre.UI.ViewModels;

namespace BuscoPre.UI.Controllers
{
	public class CategoriesController : Controller
	{
		private static readonly int Offset = 16;
		//
		// GET: /Categories/

		public ActionResult Index(string url, string id)
		{
			var searchResponse = ArticleDao.GetArticlesByCategory(16, id, url);

			var tags = new List<Tag>();

			if (searchResponse.AvailableCategories != null && searchResponse.AvailableCategories.Any())
				GenerateTagCloud(searchResponse, tags);

			var tagCloud = new TagCloud(tags);

			var viewModel = new SearchResultViewModel
			{
				Categories = searchResponse,
				TagCloud = tagCloud,
				Results = searchResponse.Articles,
				Title = searchResponse.Category.Name
			};

			return View(viewModel);
		}

		private void GenerateTagCloud(SearchResponse searchResponse, List<Tag> tags)
		{
			double max = searchResponse.AvailableCategories.Max(item => (double)item.Results);

			foreach (var item in searchResponse.AvailableCategories)
			{
				var tag = new Tag
				{
					Text = item.Name,
					NavigateUrl = string.Concat(Request.ApplicationPath, "/", item.Url)
				};

				double count = (double)item.Results;
				double percent = (count / max) * 100;

				if (percent < 20)
				{
					tag.CssClass = "TagWeight5";
				}
				else if (percent < 40)
				{
					tag.CssClass = "TagWeight4";
				}
				else if (percent < 60)
				{
					tag.CssClass = "TagWeight3";
				}
				else if (percent < 80)
				{
					tag.CssClass = "TagWeight2";
				}
				else
				{
					tag.CssClass = "TagWeight1";
				}

				tags.Add(tag);
			}
		}

		public ActionResult Result()
		{
			return View();
		}
	}
}
